#!/bin/bash

REPOS_URL="https://gitee.com/wx-rdc/gitea"

BASE_PATH="$HOME/.docker"

NETWORK_NAME="secloud-network"
MYSQL_NAME="sec-mysql"
REDIS_NAME="sec-redis"

# registry path
REGISTRY="svr01:5000"

SQL_FILES="gitea-ddl.sql"

importSQL() {
  if [ ! -f $BASE_PATH/sql/$1 ]; then
    wget -O "$BASE_PATH/sql/$1" "$REPOS_URL/raw/master/sql/$1"
    docker exec -i $MYSQL_NAME mysql -uroot -p123456 < $BASE_PATH/sql/$1
  fi
}

if [ ! -d $BASE_PATH ]; then
  mkdir -p $BASE_PATH
  mkdir -p $BASE_PATH/sql
fi

for sqlfile in $SQL_FILES; do
  importSQL $sqlfile
done

# docker exec -i $MYSQL_NAME mysql -uroot -p123456 < ./sql/gitea-ddl.sql

# ssh support
sudo wget -O "/usr/local/bin/gitea" "$REPOS_URL/raw/master/scripts/gitea"
sudo chmod +x /usr/local/bin/gitea

if [ ! -f $HOME/.ssh/id_rsa.pub ]; then
    ssh-keygen -t rsa -b 4096 -C "Gitea Host Key"
    echo "$(cat $HOME/.ssh/id_rsa.pub)" >> $HOME/.ssh/authorized_keys
fi

if [ ! -d /data/gitea ]; then
    sudo mkdir -p /data/gitea
    sudo chown -R $USER. /data/gitea
fi

docker run -d \
    --restart=always \
    --name=gitea \
    -e USER_UID=$UID \
    -e USER_GID=$UID \
    -e GITEA__database__DB_TYPE=mysql \
    -e GITEA__database__HOST=$MYSQL_NAME:3306 \
    -e GITEA__database__NAME=gitea \
    -e GITEA__database__USER=gitea \
    -e GITEA__database__PASSWD=gitea@1024 \
    -p 3022:22 \
    -p 3000:3000 \
    -v /data/gitea:/data \
    -v $HOME/.ssh/:/data/git/.ssh \
    --network $NETWORK_NAME \
    gitea/gitea:1.18.5